package com.app.tablet.view;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.app.tablet.R;
import com.app.tablet.data.dao.TabletDao;
import com.app.tablet.data.tasks.MainPageTask;
import com.app.tablet.notify.Notifier;

/**
 * This class is used for displaying added reminder records ready for editing.
 * It displays all the reminders in a list view by an asynctask.
 * On touching each reminder in the list displayed, AddPageActivity is called with the Delete button and edit button.
 * Cursor adaptor is used to populate the reminder list.
 * For this purpose an inner class is used for cursor usage.
 * @author Sega
 *
 */
public class EditPageActivity extends BaseActivity implements Notifier,	OnClickListener, OnItemClickListener {
	
	/** Following members are used as tags in log(for the purpose of following the execution flow while developing) */
	private static final String TagProject = "Tablet-Project";
	private static final String TagPage = "EditPageActivity-Page ::";

	
	/** Following members are declarations of controls */
	ListView editlist;
	Button leftBtn;
	Button rightBtn;
	TextView titletxt;
	
	/** Declaration of inner class that extends cursor adaptor */
	mycursoradaptor mycursoradap;
	
	
	/** Boolean array declaration to track the item row in displayed list */
	boolean[] isselected;
	
	/** Boolean declaration to help in choosing the other options in AddPageActivity */
	public static boolean deleteBtnBool=false;
	
	/* (non-Javadoc) This method is called whenever the activity gains control and resumes.
	 * The reminder list is freshly populated each and every time when the activity is resumed.
	 * This populating the list is done by calling the asynctask method.
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		startTask();
	}

	/* (non-Javadoc) This method is called when the activity is first created.
	 * The layout is set and the headercontent method is called.
	 * The reminder list is freshly populated each and every time when the activity is resumed.
	 * This populating the list is done by calling the asynctask method.
	 * Controls are initialised.
	 * @see com.app.tablet.view.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_editpage);
		
		setHeaderContent();

		editlist = (ListView) findViewById(R.id.list_editpage);
		editlist.setOnItemClickListener(this);
		leftBtn.setOnClickListener(this);
		
		startTask();
	}

	/**
	 * This method is used to customise the header layout.
	 * The Buttons are initialised and their texts are set.
	 * The title text is set. 
	 */
	private void setHeaderContent() {
		leftBtn = (Button) findViewById(R.id.leftHeaderBtn);
		leftBtn.setText(R.string.backBtn);

		rightBtn = (Button) findViewById(R.id.rightHeaderBtn);
		rightBtn.setVisibility(View.INVISIBLE);
		
		titletxt =(TextView)findViewById(R.id.titleHeaderTxt);
		titletxt.setText(R.string.titleEditpageTxt);
	}
	
	/**
	 * This method is used to invoke the asynctask's execute method.
	 * The class in which asynctask is defined is initialised.
	 * The progress dialog page is displayed.
	 */
	private void startTask() {
		showDialog(DIALOG_ID_PROGRESS);
		MainPageTask mainTask = new MainPageTask(this);
		mainTask.execute();
	}
	
	/* (non-Javadoc) This is a overridden method of the Notifier interface.
	 * This is used to update the UI with the output result of the executed asynctask.
	 * The output result obtained and displayed in the UI list.
	 * The output result is of type cursor.
	 * The method which uses this cursor as a input is called.
	 * @see com.app.tablet.notify.Notifier#onSuccess(java.lang.Object)
	 */
	@Override
	public void onSuccess(Object response) {
		hideProgress();
		if (response instanceof Cursor) {
			populateMainList((Cursor) response);
		}
	}

	/* (non-Javadoc) This is also a overridden method of the Notifier interface.
	 * This is used to update the UI with the error output of the executed asynctask.
	 * The error occured during the execution of asynctask is handled and notifies to the user.
	 * @see com.app.tablet.notify.Notifier#onError()
	 */
	@Override
	public Object onError() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @param mainpageCursor This method is called when the output result of the asynctask is received in UI.
	 * The cursor used is obtained from the asynctask.
	 * The inner class that extends to cursor adaptor is initialised.
	 * The list adaptor is set to this class cursor adaptor.
	 */
	private void populateMainList(Cursor mainpageCursor) {
		mycursoradap = new mycursoradaptor(this, mainpageCursor);
		isselected = new boolean[mainpageCursor.getCount()];
		editlist.setAdapter(mycursoradap);
	}

	/**
	 * This is a inner class which extends to cursor adaptor.
	 * This class is used to populate the list with the reminder records.
	 * The cursor is obtained from the execution of asynctask.
	 * Then the adaptor is also used to inflate the list items designed layout. 
	 * @author Sega
	 *
	 */
	class mycursoradaptor extends CursorAdapter {

		/** The context is defined */
		Context adcontext;

		/**
		 * @param context The context is initialised
		 * @param c
		 */
		public mycursoradaptor(Context context, Cursor c) {
			super(context, c);
			adcontext = context;
		}

		/* (non-Javadoc) This is one of the over ridden methods of the cursor adaptor class.
		 * The cursor consists the reminder records.
		 * It consists of table name, dosage, schedule and alarm time.
		 * The textview controls in the inflated layout are initialised. 
		 * Their text properties are set by the values got from the cursor.
		 * The boolean array is used to choose the selected item row and store the values in the public constants.
		 * The intent is declared and initialised to call the AddPageActivity with the selected and stored records.
		 * Form here the boolean is used to select the required features in the AddPageActivity.
		 * @see android.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor)
		 */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView txtname = (TextView) view.findViewById(R.id.txt_line1);
			TextView txtroll = (TextView) view.findViewById(R.id.txt_line2);
			TextView txtdep = (TextView) view.findViewById(R.id.txt_line3);
			txtname.setText(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_TABLET_NAME)));
			txtroll.setText((cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_DOSAGE))) + ", "
					+ (cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_SCHEDULE))));
			txtdep.setText(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_ALARM_TIME)));
			if (isselected[cursor.getPosition()]) {
				AddPageActivity.dbData.setTabletname(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_TABLET_NAME)));
				AddPageActivity.dbData.setDoasge(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_DOSAGE)));
				AddPageActivity.dbData.setSchedule(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_SCHEDULE)));
				AddPageActivity.dbData.setAlarmtime(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_ALARM_TIME)));
				AddPageActivity.dbData.setTones(cursor.getString(cursor.getColumnIndex(TabletDao.FIELD_TONES)));
				AddPageActivity.dbData.setId(cursor.getInt(cursor.getColumnIndex(TabletDao.FIELD_TABLET_ID)));
				deleteBtnBool=true;
				Intent intent = new Intent(EditPageActivity.this, AddPageActivity.class);
				startActivity(intent);
			}
		}

		/* (non-Javadoc) This is the other over ridden method of this inner class.
		 * The row view layout is inflated here.
		 * @see android.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
		 */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) adcontext.getSystemService(adcontext.LAYOUT_INFLATER_SERVICE);
			View rowview = inflater.inflate(R.layout.layout_listitem_editpage,null);
			return rowview;
		}
	}
	
	/* (non-Javadoc) This is the over ridden method of the outer main class that extends to OnClickListener
	 * Back Button click event is handled here.
	 * On click of the Back button the EditPageActivity is finished, reseting the desired variables. 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftHeaderBtn:
			AddPageActivity.reset();
			this.finish();
			break;
		}
	}

	/* (non-Javadoc) This is the over ridden method of the main clause that extends to OnItemClickListener.
	 * This where the boolean array is set to find the selected item row.
	 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		for (int index = 0; index < isselected.length; index++) {
			isselected[index] = false;
		}
		isselected[position] = true;
		Log.i(TagProject, TagPage+position);
		refreshListView();
	}
	
	/**
	 * This method is used to refresh the list.
	 * This is done in order to affect the list with the changes it has made to it.
	 */
	private void refreshListView() {
		editlist.invalidate();
		mycursoradap.notifyDataSetChanged();
	}

}